package com.xx.jicheng.service.impl;

import java.util.Random;

import org.apache.shiro.codec.Hex;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xx.jicheng.entity.Account;
import com.xx.jicheng.mapper.AccountMapper;
import com.xx.jicheng.service.ConfigService;
import com.xx.jicheng.service.SecurityService;

@Service
public class SecurityServiceImpl implements SecurityService {

	private String algorithm = ConfigService.SECURITY_ALGORITHM;
	
	@Autowired
	private AccountMapper accountMapper;

	@Override
	public String generateSalt(int n) {
		Random r = new Random();
		byte[] b = new byte[8];
		r.nextBytes(b);
		return Hex.encodeToString(b);
	}

	@Override
	public String encrypt(String plainPassword, String saltHex) {
		byte[] salt = Hex.decode(saltHex);
		SimpleHash hash = new SimpleHash(algorithm, plainPassword, salt, 1000);
		return hash.toHex();
	}
	
	@Override
	public Account login(String principals, String plainPassword) {
		Account account = accountMapper.findByPrincipals(principals);
		if(account == null){
			return null;
		}
		if(!encrypt(plainPassword, account.getSalt()).equals(account.getPassword())){
			return null;
		}
		return account;
	}

}
